package net.jgrm.product.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import net.jgrm.product.entity.Product;
import net.jgrm.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理端商品控制器
 * 专门用于管理端访问，不会记录PV/UV统计
 */
@RestController
@RequestMapping("/api/admin/products")
public class AdminProductController {

    @Autowired
    private IProductService productService;

    /**
     * 管理端根据ID查询商品（不记录PV/UV统计）
     */
    @GetMapping("/{id}")
    @SentinelResource(
            value = "admin_getProductById",
            blockHandler = "getProductByIdBlockHandler",
            fallback = "getProductByIdFallback"
    )
    public Product getProductById(@PathVariable Long id) {
        try {
            // 仅获取商品信息，不记录访问统计
            return productService.getProductById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 管理端批量查询商品
     */
    @PostMapping("/batch")
    public List<Product> getProductsByIds(@RequestBody List<Long> ids) {
        try {
            return productService.listByIds(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 管理端分页查询商品
     */
    @GetMapping("/page")
    public Map<String, Object> getProductsPage(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int size) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 这里可以集成分页查询逻辑
            result.put("success", true);
            result.put("message", "管理端分页查询接口");
            result.put("current", current);
            result.put("size", size);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    @PostMapping("save")
    public Product saveProduct(@RequestBody Product product) {
        try {
            return productService.saveProduct(product);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @PostMapping("remove/{id}")
    public Object removeProduct(@PathVariable("id") Long productId) {
        productService.removeById(productId);
        return "删除成功";
    }

    @PostMapping("remove/ids")
    public Object removeProducts(@RequestBody List<Long> ids) {
        productService.removeProductByIds(ids);
        return "删除成功";
    }

    @PostMapping("update")
    public Product updateProduct(@RequestBody Product product) {
        return productService.updateProductById(product);
    }

    /**
     * 管理端修改商品库存
     */
    @PostMapping("/{id}/stock")
    public Map<String, Object> updateProductStock(@PathVariable Long id, @RequestParam Integer quantity) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = productService.decreaseStock(id, quantity);
            result.put("success", success);
            result.put("message", success ? "库存修改成功" : "库存修改失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "库存修改失败: " + e.getMessage());
        }
        return result;
    }

    // 限流/熔断处理 - 查询商品
    public Product getProductByIdBlockHandler(Long id, BlockException e) {
        e.printStackTrace();
        Product errorProduct = new Product();
        errorProduct.setProductName("管理端请求人数过多，请稍后再试");
        return errorProduct;
    }

    /**
     * 熔断 降级处理 - 查询商品
     */
    public Product getProductByIdFallback(Long id, Throwable e) {
        e.printStackTrace();
        Product errorProduct = new Product();
        errorProduct.setProductName("管理端服务异常，请稍后再试");
        return errorProduct;
    }
}